﻿//JQuery.XPager plugin
var XPager = function() {
	//private
	var p = {};
	p.fs = function(obj) {
		obj.select(); return false;
	};
	p.jumperIsSelect = function() {
		if (p.pIndexJumper[0].tagName == "SELECT") { return true; };
		return false;
	};
	p.checkInput = function() {
		if (p.jumperIsSelect()) return true;
		var r = new RegExp("^\\s*(\\d+)\\s*$");
		if (!r.test(p.pIndexJumper.val())) { alert(p.pInvalidTip); return p.fs(p.pIndexJumper); };
		if (RegExp.$1 < 1 || RegExp.$1 > p.pMax) {
			alert(p.pOutOfRangeTip);
			return p.fs(p.pIndexJumper);
		};
		return true;
	};
	p.onSubmit = function() {
		if (!p.checkInput()) return false;
		var currentPage = parseInt(p.pIndexJumper.val());
		currentPage = (p.jumperIsSelect()) ? currentPage : currentPage - 1;
		XPager.ToPage(currentPage);
	};
	p.onPageIndexChanging = function(e) {
		if (p.jumperIsSelect()) { p.onSubmit(); return true; };

		var kcode = e.keyCode;
		var validKey = (kcode == 8 || kcode == 46 || kcode == 37 || kcode == 39 || (kcode >= 48 && kcode <= 57) || (kcode >= 96 && kcode <= 105));
		if (!validKey) {
			if (kcode == 13) p.onSubmit();
			return false;
		};
		p.pRaw = parseInt(this.value);
		return true;
	};
	p.onPageIndexChanged = function(e) {
		var _p0 = parseInt(this.value);
		if (_p0 < 1 || _p0 > p.pMax) {
			this.value = p.pRaw || 1;
		};
	};
	p.onPostBack = function(pIndex) {
		__doPostBack(p.uniqueID, pIndex); //asp.net postback method!
	};
	p.onLinkClick = function(e) {
		if (p.urlPaging) return true;
		var s = this.id.split("_");
		p.onPostBack(s[s.length - 1]);
		return false;
	};
	//public
	var pub = {};
	pub.Init = function(opts) {
		//member variables
		p.uniqueID = opts.uniqueID;
		p.pager = $("#" + opts.pagerID);
		p.pIndexJumperID = opts.pIndexJumperID;
		if (p.pIndexJumperID && p.pIndexJumperID != "") { p.pIndexJumper = $("#" + p.pIndexJumperID); };
		p.btnID = opts.btnID;
		if (p.btnID && p.btnID != "") { p.btn = $("#" + p.btnID); };
		p.pOutOfRangeTip = opts.pOutOfRangeTip;
		p.pInvalidTip = opts.pInvalidTip;
		p.pMax = opts.pMax;
		p.urlPaging = opts.urlPaging;
		p.urlPagingNewWin = opts.urlPagingNewWin;
		p.urlFormatStr = opts.urlFormatStr;
		//events
		if (p.btn) { p.btn.click(p.onSubmit); };
		if (p.pIndexJumper) {
			if (p.jumperIsSelect()) {
				p.pIndexJumper.change(p.onPageIndexChanging);
			} else {
				p.pIndexJumper.keydown(p.onPageIndexChanging);
				p.pIndexJumper.keyup(p.onPageIndexChanged);
			};
		};
		if (!p.urlPaging) {
			$("a", p.pager).click(p.onLinkClick);
		};

	};
	pub.ToPage = function(pIndex) {
		if (p.urlPaging) {
			var url0 = p.urlFormatStr.replace(/\{0\}/g, pIndex+1);
			if (p.urlPagingNewWin) {
				window.open(url0, "_blank");
			} else {
				location.href = url0;
			};
			return;
		};
		p.onPostBack(pIndex);
	};
	return pub;
} ();